﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace HttpService
{
	public class HttpUtils
	{
		string BaseAddress { get; set; }

		public HttpUtils(string baseAddress)
		{
			BaseAddress = baseAddress;
		}

		protected void ConfigureClient(HttpClient client)
		{
			client.BaseAddress = new Uri(BaseAddress);
			client.DefaultRequestHeaders.Accept.Clear();
			client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
		}

		public HttpResponseMessage SendPostMessage(string uri, object contentObject)
		{
			using (HttpClient client = new HttpClient())
			{
				ConfigureClient(client);
				StringContent content = new StringContent(JsonConvert.SerializeObject(contentObject));
				content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
				var task = client.PostAsync(uri, content);
				task.Wait();
				return task.Result;
			}
		}

		public HttpResponseMessage SendPutMessage(string uri, object contentObject)
		{
			using (HttpClient client = new HttpClient())
			{
				ConfigureClient(client);
				StringContent content = new StringContent(JsonConvert.SerializeObject(contentObject));
				content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
				var task = client.PutAsync(uri, content);
				task.Wait();
				return task.Result;
			}
		}

		public HttpResponseMessage SendDeleteMessage(string uri)
		{
			using (HttpClient client = new HttpClient())
			{
				ConfigureClient(client);
				var task = client.DeleteAsync(uri);
				task.Wait();
				return task.Result;
			}
		}

		public HttpResponseMessage SendGetMessage(string uri)
		{
			using (HttpClient client = new HttpClient())
			{
				ConfigureClient(client);
				var task = client.GetAsync(uri);
				task.Wait();
				return task.Result;
			}
		}

		public T SendGetJsonMessage<T>(string uri)
		{
			using (HttpClient client = new HttpClient())
			{
				ConfigureClient(client);
				var task = client.GetStringAsync(uri);
				task.Wait();
				string jsonString = task.Result;
				T item = JsonConvert.DeserializeObject<T>(jsonString);
				return item;
			}
		}

		public object SendGetJsonMessage(string uri, Type type)
		{
			using (HttpClient client = new HttpClient())
			{
				ConfigureClient(client);
				var task = client.GetStringAsync(uri);
				task.Wait();
				string jsonString = task.Result;
				object item = JsonConvert.DeserializeObject(jsonString, type);
				return item;
			}
		}
	}
}
